import java.util.*;

/**
 * @Author ZhangCuirong
 * @Date 2025/8/14 8:52
 * @description:
 */
public class Solution239 {
    public int[] maxSlidingWindow(int[] nums, int k) {
        PriorityQueue<int[]> heap = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] pair1, int[] pair2) {
                return pair1[0] != pair2[0] ? pair2[0] - pair1[0] : pair2[1] - pair1[1];
            }
        });
        int[] res = new int[nums.length - k + 1];
        for (int i = 0; i < k; i++) {
            heap.add(new int[]{nums[i], i});
        }
        res[0] = heap.peek()[0];
        for (int i = k; i < nums.length; i++) {
            heap.offer(new int[]{nums[i], i});
            while (heap.peek()[1] <= i - k) {
                heap.poll();
            }
            res[i - k + 1] = heap.peek()[0];
        }
        return res;
    }
    public int[] maxSlidingWindow2(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k <= 0) {
            return new int[0];
        }

        int n = nums.length;
        int[] res = new int[n - k + 1];
        int resIndex = 0;

        // 单调递减队列：存储元素的索引（而非值），确保队列中元素对应的数值递减
        Deque<Integer> deque = new LinkedList<>();

        for (int i = 0; i < n; i++) {
            // 1. 移除队列中超出当前窗口的元素（索引 <= i - k 的元素）
            while (!deque.isEmpty() && deque.peekFirst() <= i - k) {
                deque.pollFirst();
            }

            // 2. 移除队列中所有比当前元素小的元素（它们不可能成为后续窗口的最大值）
            while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
                deque.pollLast();
            }

            // 3. 将当前元素索引加入队列
            deque.offerLast(i);

            // 4. 当窗口形成后（i >= k - 1），队头就是当前窗口的最大值
            if (i >= k - 1) {
                res[resIndex++] = nums[deque.peekFirst()];
            }
        }

        return res;
    }

    public static void main(String[] args) {
        Solution239 solution = new Solution239();
        int[] nums = {1, -1};
        int[] res = solution.maxSlidingWindow(nums, 1);
        System.out.println(Arrays.toString(res));
    }
}
